//
// Created by Sugars Mac on 2020/6/1.
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

#define PASSLEN 12   // 密码长度
#define NAMELEN 24   // 用户名长度


typedef struct user_tb{
    char password[PASSLEN];
    char username[NAMELEN];
} UserTable_t; // 存储于文件中的注册用户结构

int main(){
    int fd;
    UserTable_t * table = NULL, *ptr = NULL;
    int unum = 0;

    table = (UserTable_t *)malloc(sizeof(UserTable_t) * 2);
    ptr = table;
    strcpy(ptr->username, "Victor");
    strcpy(ptr->password, "123");
    ptr++;
    strcpy(ptr->username, "Ben");
    strcpy(ptr->password, "abc");

    fd = open("user.dat", O_WRONLY);

    ptr = table;
    write(fd, ptr++, sizeof(UserTable_t));
    write(fd, ptr, sizeof(UserTable_t));

    close(fd);

//    char nums[4];
//    char *stop;
//    fgets(nums, 4, pFile);
//    unum = (int)strtol(nums, &stop, 10);
//    printf("There are %d users\n", unum);
//    printf("sizeof(UserTable_t) = %lu\n", sizeof(UserTable_t));
//    table = (UserTable_t *)malloc(sizeof(UserTable_t) * 2);

    fd = open("user.dat", O_RDONLY);

    UserTable_t * buf;
    buf = (UserTable_t*)malloc(sizeof(UserTable_t));

    int size = 1;
    while (size){
       size = read(fd, buf, sizeof(UserTable_t));
       if (-1 == size){
           close(fd);
           printf("read file error occurs\n");
           return -1;
       } else {
           if(size > 0){
               printf("read %d bytes:", size);
               printf("username: %s, password: %s\n", buf->username, buf->password);
               memset(buf, 0, sizeof(UserTable_t));
           } else {
               printf("reach the end of file\n");
           }
       }
    }
    return 0;
}